import axios from 'axios'
import config from "@/config/index.js";
import utils from "@/utils/utils.js";
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'
let { baseUrl } = config

const request = (options = {}) => {
  return new Promise((resolve, reject) => {
    let headers = {
      "content-type": "application/json",
    }
    options.headers = { ...headers, ...options.headers }
    //如果有token
    if (getToken()) options.headers['accessToken'] = getToken()

    let obj = {
      url: baseUrl + options.url || '',
      method: options.method.toLocaleUpperCase() || 'GET',
      headers: options.headers
    }

    //只筛选入参里面有值的参数
    let optionsData = utils.extractValidKeys(options.data);
    switch (options.method) {
      case "get":
        obj.params = optionsData || {}
        break;
      case "post":
        obj.data = optionsData || {}
        break;
      default:
        break;
    }
    axios(obj).then(async data => {
      if (data.data.code == 200) {
        resolve(data.data.data);
      } else if (data.data.code == 401) {
        utils.showToast("登录已失效,请重新登录", 0)
        await useUserStore().logOut()
        setTimeout(() => {
          location.href = '/index';
        }, 1000);
      }
      else {
        utils.showToast(data.data.message, 0)
        reject(data.data.message)
      }
    }).catch(error => {
      utils.showToast(error, 0)
      reject(error)
    })
  });
}

const get = (url, data, options = {}) => {
  options.method = 'GET';
  options.data = data;
  options.url = url;
  return request(options)
}

const post = (url, data, options = {}) => {
  options.method = 'POST';
  options.data = data;
  options.url = url;
  return request(options)
}


export default {
  request,
  get,
  post
}
